from machine import Pin, ADC
from device import Device

class PhotoSensor(Device):
    """光照传感器设备"""
    
    def __init__(self, name, pin_number=26):
        super().__init__(name)
        self.pin_number = pin_number
        self.sensor = None
    
    def initialize(self):
        """初始化光照传感器"""
        try:
            self.sensor = ADC(Pin(self.pin_number))
            self.initialized = True
            return True
        except Exception as e:
            print(f"光照传感器初始化失败: {e}")
            return False
    
    def read_data(self):
        """读取光照数据，返回原始值和百分比"""
        if not self.initialized or not self.sensor:
            return None
            
        try:
            # 读取原始值 (0-65535)
            light_value = self.sensor.read_u16()
            # 转换为百分比 (0-100)
            light_percent = int((light_value / 65535) * 100)
            
            return {
                "raw_value": light_value,
                "percentage": light_percent
            }
        except Exception as e:
            print(f"读取光照传感器数据错误: {e}")
            return None